import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

/// dialog工具
class DialogUtils {
  /// 判定是否弹出
  bool _isShowing = false;

  /// 上下文
  late BuildContext? _context;

  /// 布局
  late Widget? _layoutWidget;

  DialogUtils(BuildContext context) {
    _context = context;
  }

  /// 设置布局
  void setLayoutWidget(Widget value) {
    _layoutWidget = value;
  }

  /// 显示弹窗
  bool show() {
    if (_isShowing && _layoutWidget == null) {
      return false;
    }
    showDialog<bool>(
      context: _context!,
      barrierColor: Colors.black.withOpacity(0.5),
      barrierDismissible: false,
      builder: (BuildContext context) {
        return WillPopScope(onWillPop: () async => false, child: _layoutWidget!);
      },
    );
    _isShowing = true;
    return true;
  }

  /// 隐藏弹窗
  Future<bool> dismiss({bool waitAnimatedRunningEnd = false, int milliseconds = 150}) async {
    if (_isShowing && _context != null) {
      _isShowing = false;
      Navigator.pop(_context!);
      if (waitAnimatedRunningEnd) {
        return await Future.delayed(Duration(milliseconds: milliseconds), () => true);
      }
      return true;
    }
    return false;
  }

  /// 销毁方法
  void dispose() {
    _layoutWidget = null;
    _context = null;
  }
}
